Dictionaries

Dictionary is a set of key-value pairs, where value is any hashable object. As Lists are indexed by integers, Dictionries are indexed by keys.

Creating Dictionaries

  • Creating an Empty Dictionary
    x = {}      # {} denotes dictionary type (not set)
          x = dict()
    
  • Creating Dictionary with initial values
    x = {'eight':8,'nine':9}
    

In [1]:
x = {'eight':8,'nine':9}

In [2]:
x['eight']


Out[2]:
8

In [3]:
x[0]


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-3-1ae75c28907a> in <module>()
----> 1 x[0]

KeyError: 0

If a key is not present in Dictionary, KeyError is raised


In [4]:
x['zero'] = 0 # Adding a key-value to dictionary
x


Out[4]:
{'eight': 8, 'nine': 9, 'zero': 0}

In [5]:
del x['nine']  # Deleting based on key
x


Out[5]:
{'eight': 8, 'zero': 0}

In [6]:
'zero' in x    # Only key membership can be checked


Out[6]:
True

Dictionary Methods

If d is a dictionary

  • d.keys() returns a view of d's keys
  • d.values() returns a view of d's values
  • d.items() returns a view of d's key-value pairs

In [7]:
x


Out[7]:
{'eight': 8, 'zero': 0}

In [8]:
x.keys()


Out[8]:
dict_keys(['zero', 'eight'])

In [9]:
x.values()


Out[9]:
dict_values([0, 8])

In [10]:
x.items()


Out[10]:
dict_items([('zero', 0), ('eight', 8)])

In [12]:
for k,v in x.items():
    print("{} = {}".format(k,v))


zero = 0
eight = 8

Dictionary Values can be any hashable object. This means they can be lists, tuples,... . Using Dictionaries, one can implement an Adjacency List Representation of Graph Data Structure.